<?php

namespace app\admin\controller\note;

use app\admin\model\facrm\customer\Contacts;
use app\admin\model\note\Week;
use app\admin\model\note\Day;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * Ai成长服务
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\note\Order
     */
    protected $model = null;

	protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\note\Order;
        $this->view->assign("isMemoryList", $this->model->getIsMemoryList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

	/**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->with(['user','customer','contact'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

	public function add(){
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
			$params['end_time'] = date('Y-m-d 23:59:59',strtotime($params['start_time']) + ($params['service_days'] * 24 *3600));
			if(!$params['customer_id'] && !$params['contact_id']){
				$contact = Contacts::where(['uid' => $params['uid']])->find();
			}else{
				$contact_where = [];
				if($params['customer_id']) $contact_where['customer_id'] = $params['customer_id'];
				if($params['contact_id']) $contact_where['id'] = $params['contact_id'];
				$contact = Contacts::where($contact_where)->find();
			}
			$params['customer_id'] = $contact->customer_id;
			$params['contact_id'] = $contact->id;
            $result = $this->model->allowField(true)->save($params);

			//创建周
			$weekModel = new Week();
			$dayModel = new Day();
			$where = [];
			if($params['uid']) $where['uid'] = $params['uid'];
			if($params['contact_id']) $where['contact_id'] = $params['contact_id'];
			$allDays = $dayModel->where($where)->column('date_text');
			$week_id = 0;

			$dayDatas = [];
			for($n = 0; $n<=$params['service_days']; $n++){
				$date_time = strtotime($params['start_time'] .' + '.$n.'days');
				$date_text = date('Y-m-d',$date_time);
				$week_day = date('w',$date_time);

				// 创建周数据
				if($week_day == 0 || !$week_id){
					$nowWeek = $weekModel->where(['start_time'=>['<=',$date_time],'end_time'=>['>',$date_time],'uid'=>$params['uid']])->find();
					if($nowWeek){
						$week_id = $nowWeek->id;
					}else{
						$week_num = $weekModel->where(['uid'=>$params['uid']])->max('week') + 1;
						$weekData = [
							'uid' => $params['uid'],
							'customer_id' => $contact->customer_id,
							'contact_id' => $contact->id,
							'week' => $week_num,
							'start_time' => $date_time,
							'end_time' => strtotime('next Sunday', $date_time) - 1,
						];
						$week = Week::create($weekData);
						$week_id = $week->id;
					}
				}

				if(!in_array($date_text,$allDays)){
					$dayDatas[] = [
						'week_id' => $week_id,
						'uid' => $params['uid'],
						'customer_id' => $contact->customer_id,
						'contact_id' => $contact->id,
						'week_day' => $week_day,
						'date_time' => $date_time,
						'date_text' => $date_text,
					];
				}
			}
			$dayModel->saveAll($dayDatas);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

	public function edit($ids = null){
		return parent::edit($ids);
	}
}